﻿using System;

namespace DomainNamespace
{
    public class Queue
    {
        private int _length;

        private QueueItem firstItem;
        private QueueItem lastItem;

        public Queue() 
        {
            _length = 0;
            firstItem = null;
            lastItem = null;
        }

        public int length
        {
            get { return _length; }
        }

        public void addValue(Object newValue)
        {
            QueueItem newItem = new QueueItem(newValue);
            if (_length == 0)
            {
                firstItem = newItem;
                lastItem = newItem;
            }
            else
            {
                lastItem.setRightItem(newItem);
                newItem.setLeftItem(lastItem);
                lastItem = newItem;
            }
            _length++;
        }

        public Object getValue()
        {
            Object retVal;
            if (length == 0)
            {
                throw new System.Exception();
            }
            else
            {
                retVal = firstItem.getValue();
                removeFirstItem();
            }
            return retVal;
        }

        private void removeFirstItem()
        {
            if (firstItem != null)
            {
                QueueItem itemForRemove = firstItem;
                if (length - 1 == 0)
                {
                    firstItem = null;
                    lastItem = null;
                }
                else
                {
                    firstItem = itemForRemove.getNextItem();
                    firstItem.setLeftItem(null);

                }
                itemForRemove.setLeftItem(null);
                itemForRemove.setRightItem(null);
                _length--;
            }
        }

        public Object readItem(int index)
        {
            Object retVal = null;
            if (index >= 0 && index < length)
            {
                QueueItem currItem = firstItem;
                for (int i = 0; i < index; i++)
                {
                    currItem = currItem.getNextItem();
                }
                retVal = currItem.getValue();
            }
            else
            {
                throw new System.Exception();
            }
            return retVal;
        }

        public void clean()
        {
            while (length != 0)
            {
                this.getValue();
            }
        }
    }
}
